package com.mdp.im.core.subscriber.action.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mdp.core.api.Sequence;
import com.mdp.im.core.scbscriber.api.action.ScbscriberAction;
import com.mdp.im.core.socket.ChannelsHolder;
import com.mdp.im.core.subscriber.action.AbstractSubscriberAction;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 离开群组处理器
 * 
 * @author chenyc
 * @date 2018/6/12
 */
@Service
public class LeaveChannelGroupAction extends AbstractSubscriberAction implements ScbscriberAction {

	@Autowired
    Sequence seqService;
	
	
    /**
     * 成员离开群
     * 1.发送群通知
     * 2.将人员从数据库 group_user表移除
     * 3.将人员从服务器组移除
     * 
     * @param message
     * message:{ 
     *  action:'leaveChannelGroup',
     *  msgType:'group',  
     *  sendUserid:'发送者编号',
     *  sendUsername:'发送者姓名', 
     *  cuserid:'群主',
     * 	groupId:'群组编号不能为空',
     *  groupName:'群组名称不能为空',
     *  users:{
     *  	userid:'成员编号'
     *  	username:'成员名称'
     *  }
     * }
     * 
     * 
     */
    @Override
    public void doAction(JSONObject message) {
        JSONObject json = message;
        if (!json.containsKey("users")) {
            return;
        } 
        String groupId=json.getString("groupId");  
        JSONArray jsonUsers=json.getJSONArray("users"); 
        handleMessageWithGroup(message, true, groupId); //必须先发消息后删除
        for (Object user : jsonUsers) {
        	JSONObject jsonUser=(JSONObject)user;
        	String userid=jsonUser.getString("userid"); 
            Set<String> channelIdSet = ChannelsHolder.getChannelIdsByUserid(userid);
            if (channelIdSet != null) { 
                for (String imChannelId : channelIdSet) {
                    Channel imChannel = ChannelsHolder.getChannelById(imChannelId);
                    if(imChannel == null) {
                        continue;
                    }
                    
                    ChannelsHolder.removeChannelFromGroup(groupId, imChannel);       
                }
            }
        }  
        
        
    }

}
